package com.fileupload;

import com.fileupload.monitor.MonitorManager;
import com.fileupload.upload.log.BatchLogCollectorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * 应用程序主入口
 * @author 小乙
 */
@SpringBootApplication
@EnableScheduling
public class FileUploadApplication {

    private static final Logger logger = LoggerFactory.getLogger(FileUploadApplication.class);

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(FileUploadApplication.class, args);
        
        // 注册JVM关闭钩子，实现优雅停机
        registerShutdownHook(context);
    }
    
    /**
     * 注册JVM关闭钩子，用于优雅停机
     * 1. 停止扫描文件线程，同时注销所有文件夹的监听
     * 2. 等待日志数据保存完成后，再关闭程序
     * 
     * @param context Spring应用上下文
     */
    private static void registerShutdownHook(ConfigurableApplicationContext context) {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            logger.info("开始优雅停机流程...");
            
            try {
                // 步骤1: 停止所有监控器
                logger.info("正在停止文件监控器...");
                MonitorManager monitorManager = context.getBean(MonitorManager.class);
                monitorManager.stopAllMonitors();
                logger.info("所有文件监控器已停止");
                
                // 步骤2: 等待日志数据保存完成
                logger.info("正在等待日志数据保存完成...");
                BatchLogCollectorService logCollectorService = context.getBean(BatchLogCollectorService.class);
                boolean logSaveResult = logCollectorService.executeBatchInsert();
                logger.info("日志数据保存{}", logSaveResult ? "成功" : "失败");
                
                // 给日志保存一些额外时间
                Thread.sleep(1000);
                
            } catch (Exception e) {
                logger.error("优雅停机过程中发生异常: {}", e.getMessage(), e);
            } finally {
                // 关闭Spring上下文
                context.close();
                logger.info("优雅停机完成");
            }
        }, "ShutdownHook-Thread"));
        
        logger.info("优雅停机钩子已注册");
    }
}